#ifndef AUDIOCAPTURE_H
#define AUDIOCAPTURE_H

#include <QObject>
#include <QAudioSource>
#include <QAudioDevice>
#include <QAudioFormat>
#include <QMediaDevices>
#include <QIODevice>
#include <QTimer>
#include <QByteArray>
#include <QQueue>
#include <QMutex>
#include <QWaitCondition>
#include <QThread>

class AudioCapture : public QObject
{
    Q_OBJECT

public:
    explicit AudioCapture(QObject *parent = nullptr);
    ~AudioCapture();

    bool startCapture();
    void stopCapture();
    bool isCapturing() const;

    // 音频传输相关
    void setTransmissionEnabled(bool enabled);
    void setTransmissionHost(const QString &host);
    void setTransmissionPort(quint16 port);
    bool startTransmission();
    void stopTransmission();
    bool isTransmitting() const;

signals:
    void captureStatusChanged(bool isCapturing);
    void captureError(const QString &error);
    void audioDataReady(const QByteArray &data);
    
    // 传输相关信号
    void transmissionStatusChanged(bool isTransmitting);
    void transmissionError(const QString &error);
    void transmissionDataSent(qint64 bytesSent);

private slots:
    void onAudioDataReady();
    void onAudioSourceStateChanged(QAudio::State state);
    void onTransmissionTimer();

private:
    void setupAudioFormat();
    bool initializeAudioCapture();
    void processAudioData(const QByteArray &data);
    void sendAudioData(const QByteArray &data);

private:
    // 音频相关
    QAudioSource *m_audioSource;
    QAudioDevice m_audioDevice;
    QAudioFormat m_audioFormat;
    QIODevice *m_audioIODevice;
    
    // 状态
    bool m_isCapturing;
    
    // 音频参数
    static const int SAMPLE_RATE = 48000;
    static const int CHANNEL_COUNT = 2;
    static const int SAMPLE_SIZE = 16;
    static const int BUFFER_SIZE = 4096;
    
    // 传输相关
    bool m_transmissionEnabled;
    QString m_transmissionHost;
    quint16 m_transmissionPort;
    QTimer *m_transmissionTimer;
    QQueue<QByteArray> m_audioQueue;
    QMutex m_audioQueueMutex;
    QWaitCondition m_audioQueueCondition;
    
    // 音频处理线程
    class AudioProcessingThread;
    AudioProcessingThread *m_processingThread;
};

class AudioCapture::AudioProcessingThread : public QThread
{
    Q_OBJECT

public:
    explicit AudioProcessingThread(AudioCapture *parent);
    void addAudioData(const QByteArray &data);
    void stopProcessing();

signals:
    void audioDataProcessed(const QByteArray &data);

protected:
    void run() override;

private:
    AudioCapture *m_parent;
    QQueue<QByteArray> m_dataQueue;
    QMutex m_queueMutex;
    QWaitCondition m_queueCondition;
    bool m_running;
};

#endif // AUDIOCAPTURE_H
